891C - Envy - CodeForces Solution


data structures dsu graphs *2300

Please click on ads to support us..

C++ Code:

#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#include<cmath>
#include<set>
#define PII pair<int, int>
#define LL int 
#define PLL pair<LL, LL>
using namespace std;
#define N 500010
LL f[N],si[N];

vector<pair<LL&,LL>>his_fa,his_si;
map<LL,vector<LL> >pos[N];
vector<LL>g[N];
LL ans[N];
struct node
{
    LL u,v,w;
}a[N];
LL n,m;
LL find(LL x)
{
    while(x!=f[x])x=f[x];
    return f[x];
}
void merge(LL x,LL y)
{
    x=find(x);
    y=find(y);
    if(x!=y)
    {
        if(si[x]<si[y])swap(x,y);
        his_fa.push_back({f[y],f[y]});
        f[y]=x;
        his_si.push_back({si[y],si[y]});
        si[x]+=si[y];
    }
}
LL history()
{
    return his_fa.size();
}
void roll(LL h)
{
    while(his_fa.size()>h)
    {
        his_fa.back().first=his_fa.back().second;
        his_fa.pop_back();
        his_si.back().first=his_si.back().second;
        his_si.pop_back();
    }
}

void solve()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        f[i]=i;
        si[i]=1;
    }
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d",&a[i].u,&a[i].v,&a[i].w);
        g[a[i].w].push_back(i);
    }
    LL q;
    scanf("%d",&q);
    for(int i=1;i<=q;i++)
    {
        LL k;
        scanf("%d",&k);
        for(int j=1;j<=k;j++)
        {
            LL idx;
            scanf("%d",&idx);
            pos[a[idx].w][i].push_back(idx);
        }
    }
    for(int i=1;i<=5e5;i++)
    {
        for(auto it:pos[i])
        {
            LL v=it.first;
            LL h=history();
            for(auto j:it.second)
            {
                if(find(a[j].u)==find(a[j].v))ans[v]=-1;
                merge(a[j].u,a[j].v);
            }
            roll(h);
        }
        for(auto it:g[i])merge(a[it].u,a[it].v);
    }
    for(int i=1;i<=q;i++)
        if(ans[i]==0)printf("YES\n");
        else printf("NO\n");
}
int main()
{
    solve();
    return 0;
}


Comments

Submit
0 Comments
More Questions

14B - Young Photographer
143A - Help Vasilisa the Wise 2
320A - Magic Numbers
1658A - Marin and Photoshoot
514A - Chewbaсca and Number
382A - Ksenia and Pan Scales
734B - Anton and Digits
1080A - Petya and Origami
1642D - Repetitions Decoding
1440A - Buy the String
1658F - Juju and Binary String
478A - Initial Bet
981A - Antipalindrome
365A - Good Number
1204B - Mislove Has Lost an Array
1409D - Decrease the Sum of Digits
1476E - Pattern Matching
1107A - Digits Sequence Dividing
1348A - Phoenix and Balance
1343B - Balanced Array
1186A - Vus the Cossack and a Contest
1494A - ABC String
1606A - AB Balance
1658C - Shinju and the Lost Permutation
1547C - Pair Programming
550A - Two Substrings
797B - Odd sum
1093A - Dice Rolling
1360B - Honest Coach
1399C - Boats Competition